//
//  ZMStatusViewModel.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/26.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
import YYText

class ZMStatusViewModel: NSObject {
   //viewmodel管理的model
    var statusesModel : ZMStatusesModel?{
        didSet{
            
            //处理会员等级图片逻辑
            handleMbrankImage(mbrank: statusesModel?.user?.mbrank ?? 0)
            //处理认证类型等级图片
            verifiedtype(type: statusesModel?.user?.verified_type ?? -1)
            
            if let currentStatusModel = statusesModel {
                handleRetweetedStatus(retweetStatusModel: currentStatusModel)
            }
            
            //处理微博来源
            handlesourceContent(source: statusesModel?.source ?? "")
            //处理微博问been
          originalAttributedStr =  handleAttributedString(text: statusesModel?.text ?? "" , isOriginal: true)
            
            retweedStatusesAttributeStr = handleAttributedString(text: statusesModel?.retweeted_status?.text ?? "", isOriginal: false)
        }
    }
    
    var mbrankImage : UIImage?
    
    //认证等级图片
    var verifiedTypeImage : UIImage?
    
    //转发微博内容
    var retweetContent : String?
    
    //原创微博富文本
    var originalAttributedStr: NSAttributedString?
    //转发微博富文本
    var retweedStatusesAttributeStr: NSAttributedString?
    
    
    //处理微博转变成富文本
    private func handleAttributedString(text: String,isOriginal:Bool)->NSAttributedString{
        
        //默认原创微博字体大小
        var fontSize: CGFloat = 14
        //默认原创微博显示富文本的颜色
        var color = UIColor.darkGray
        if isOriginal == false {
            //转发微博字体大小
            fontSize = 13
            //转发微博显示富文本的颜色
            color = UIColor.lightGray
        }
       
        
        //将微博内容转变成富文本
        let attributedStr = NSMutableAttributedString(string: text)
        
        //使用正则表达是处理富文本中的表情
        let matchResultArray = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: []).matches(in: text, options: [], range: NSMakeRange(0, (text as NSString).length))
        //遍历匹配结果,倒叙替换表情描述为表情
        for matchresult in matchResultArray.reversed() {
            //获取表情描述的范围
            let chsRange = matchresult.range
            //获取表情描述
            let chs = (text as NSString ).substring(with: chsRange)
            //根据表情描述获取表情描述
            if let emotion = ZMEmotiontools.sharedTools.selectEmotionWith(chs: chs){
                //获取图片对象
                let image  =  UIImage(named: emotion.path!,in: ZMEmotiontools.sharedTools.emotionBundle,compatibleWith: nil)!
                
                //表情富文本
             //   let emotionAttrbuiteStr = NSAttributedString.attributedStringWith(emotionModel: emotion, font: UIFont.systemFont(ofSize: 14))
                
                //注意:图片转富文本需要使用yytext
                let emotionAttributedStr = NSAttributedString.yy_attachmentString(withEmojiImage: image, fontSize: 14)!
                
                //根据表情描述的范围替换表情富文本
                attributedStr.replaceCharacters(in: chsRange, with: emotionAttributedStr)
            }
        }
        //统一设置富文本字体的大小
        attributedStr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: fontSize),NSForegroundColorAttributeName: color], range: NSMakeRange(0, attributedStr.length))
        
        //添加富文本高亮
        //在转发微博中匹配需要高亮的字符串
       addHightedAttributedString(pattern: "@[^:]+", attributedStr: attributedStr)
        addHightedAttributedString(pattern: "#[^#]+#", attributedStr: attributedStr)
        addHightedAttributedString(pattern: "http[s]?://[^\\s\\u4e00=\\u9fa5]+", attributedStr: attributedStr)

        
        
        
        
        return attributedStr
        
    }
    
    
    private func addHightedAttributedString(pattern: String,attributedStr: NSMutableAttributedString){
        //使用正则表达式筛选需要设置高亮的文字
        let highlitedMatchResultArray = try! NSRegularExpression(pattern: pattern, options: []).matches(in: attributedStr.string, options: [], range: NSMakeRange(0, (attributedStr.string as NSString).length))
        //遍历正则匹配结果
        for highlitedMatchResult in highlitedMatchResultArray {
            //获取高亮文字的范围
            let hightliedRange = highlitedMatchResult.range
            //高亮文字的颜色
            let color = UIColor(red: 80/255, green: 125/255, blue: 215/255, alpha: 1)
            //设置指定范围的富文本的文字颜色
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: color, range: hightliedRange)
            //  设置点击高亮背景色
            let bgColor = UIColor(red: 177 / 255, green: 215 / 255, blue: 255 / 255, alpha: 1)
            //使用yytext设置文本的高亮状态
               let textHightlied = YYTextHighlight()
            //创建文本边框填充颜色
            let  textboard = YYTextBorder(fill: bgColor, cornerRadius: 5)
            //设置内容内边距
            textboard.insets = UIEdgeInsets(top: 3, left: 0, bottom: 0, right: 0)
            
            //设置高亮背景边框对象
            textHightlied.setBackgroundBorder(textboard)
            
            //设置高亮
            attributedStr.yy_setTextHighlight(textHightlied, range: hightliedRange)
        }
        
    }
    
    
    
    //微博来源
    var sourceContent: String?
    //微博发布时间
    var timecontent: String?{
        
        guard let creatAt = statusesModel?.created_at else {
            return nil
        }
        
        let dt  = DateFormatter()
        
        //判断是不是今年发布的微博
        if isThisYear(creatAt: creatAt){
            //判断是不是今天,创建日历对象
            let calendar = Calendar.current//获取当前日历
            if calendar.isDateInToday(creatAt){
                //是今天
                //获取发微博时间距离当前时间的秒数
                let timeInterval = abs(creatAt.timeIntervalSinceNow)
                if timeInterval < 60 {
                    //一分钟以内,显示刚刚
                    return "刚刚"
                }else if timeInterval < 3600{
                    //一个小时以内
                    let result = timeInterval/60
                    return "\(Int(result))分钟前"

                }else{
                    //今天的其它时间
                    let result = timeInterval/3600
                    return "\(Int(result))小时前"
                }
                
                
                
            }else if calendar.isDateInYesterday(creatAt){
                //是昨天
                dt.dateFormat = "昨天 HH:mm"
            }else{
                //其他
                dt.dateFormat = "MM-dd HH:mm"
            }
            
            
            
            
        }else{
            //不是今年
            dt.dateFormat = "yyyy-MM-dd HH:mm"
        }
        
        
        return dt.string(from: creatAt)
    }
    
    
    
    //根据发微博时间判断是否是今年
    private func isThisYear(creatAt:Date)->(Bool){
        
        //创建时间格式
        let dFormat = DateFormatter()
        //仅获取年份的格式
        dFormat.dateFormat = "yyyy"
        //获取发微博的年份
        let creatatYear = dFormat.string(from: creatAt)
        
        return creatatYear == dFormat.string(from: Date())
        
    }
    
    
    //对微博来源信息进行截取处理
    func handlesourceContent(source: String){
        
        //对来源信息解包
        guard let startrang = source.range(of: "\">"),let endrang = source.range(of: "</") else {
            sourceContent = ""
            return
        }
        //获取字符串中的最大光标位置
        let startIndex = startrang.upperBound
        //获取光标的最小光标位置
        let endindex = endrang.lowerBound
        
        //根据范围截取需要的字符串
        let substr = source.substring(with: startIndex..<endindex)
        sourceContent = substr
        
    }
    
    
    
    //处理转发微博内容
    func handleRetweetedStatus(retweetStatusModel:ZMStatusesModel) -> Void {
        
        if let retweetStatus = retweetStatusModel.retweeted_status{
            
            //获取用户昵称和转发微博内容
            if let screenName = retweetStatus.user?.screen_name,let text = retweetStatus.text {
                retweetContent = "@\(screenName): \(text)"
            }
            
        }
        
    }
    
    
    
    
    
    private func verifiedtype(type:Int){
        
        switch type {
        case 0:
            verifiedTypeImage = UIImage(named: "avatar_vip")
        case 2,3,5:
            verifiedTypeImage = UIImage(named: "avatar_enterprise_vip")

        case 220:
            verifiedTypeImage = UIImage(named: "avatar_grassroot")

        default:
            verifiedTypeImage = nil
        }
        
    }
    
    
    //  处理会员等级图片（mbrank 对应的图片）
    private func handleMbrankImage(mbrank: Int) {
        if mbrank >= 1 && mbrank <= 6 {
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        } else {
            mbrankImage = nil
        }
    }
    
}
